package cn.gailvlun.gll.presentation.chat

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import cn.gailvlun.gll.R
import cn.gailvlun.gll.bean.PlaceHolder
import cn.gailvlun.gll.chatlib.db.ChatDB2
import cn.gailvlun.gll.chatlib.event.RoomCloseEvent
import cn.gailvlun.gll.chatlib.message.Message
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.ListRes
import cn.gailvlun.gll.net.Member
import cn.gailvlun.gll.net.apartment.room.Room
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.chat.adapter.GroupSettingAdapter
import cn.gailvlun.gll.presentation.xroom.adapter.NormalDialog
import cn.gailvlun.gll.util.*
import cn.gailvlun.gll.widget.OnCancelListener
import cn.gailvlun.gll.widget.OnConfirmListener
import io.reactivex.Observable
import io.realm.Realm
import kotlinx.android.synthetic.main.activity_group_setting.*
import org.greenrobot.eventbus.EventBus
import rx_activity_result2.Result
import rx_activity_result2.RxActivityResult

class GroupSettingActivity : BaseActivity() {

    companion object {
        fun openActivity(context: Activity, roomId: Int): Observable<Result<Activity>> {
            return RxActivityResult.on(context)
                    .startIntent(Intent(context, GroupSettingActivity::class.java).apply {
                        putExtra("roomId", roomId)
                    })
        }
    }

    private var mAdapter: GroupSettingAdapter? = null
    private var mLayoutManager: GridLayoutManager? = null

    override fun initComponent() {
        setContentView(R.layout.activity_group_setting)

        mAdapter = GroupSettingAdapter(mContext)
        recycler_view.adapter = mAdapter
        recycler_view.addItemDecoration(GridPaddingItemDecoration(7, DensityUtil.dp2px(mContext, 10f), 0))

        mLayoutManager = GridLayoutManager(mContext, 7)
        recycler_view.layoutManager = mLayoutManager
    }

    override fun createHandler() {
        nbv.setOnBackListener {
            onBackPressed()
        }
        tv_delete.setOnClickListener {
            NormalDialog(mContext, "确定删除并退出群聊吗？", "删除并退出的同时，将删除消息记录").apply {
                onConfirmListener = object : OnConfirmListener<Any> {
                    override fun onConfirm(dialog: Dialog, data: Any?) {
                        HttpMethods.getGroupService()
                                .deleteMember(member.id)
                                .compose(RxUtil.applyScheduler())
                                .compose(bindToLifecycle())
                                .subscribe(object : HttpSubscriber<PlaceHolder>() {
                                    override fun onSuccess(response: PlaceHolder?) {


                                        realm!!.executeTransaction { realm ->
                                            realm.where(Message::class.java)
                                                    .equalTo("dialogId", "room:${mRoom.id}")
                                                    .findAll()
                                                    .deleteAllFromRealm()
                                        }
                                        EventBus.getDefault().post(RoomCloseEvent(mRoom.id))
                                        finish()
                                    }

                                    override fun onFailure(errMsg: String?, response: PlaceHolder?, code: Int) {
                                        DialogUtil.showError(mContext, errMsg)
                                    }

                                })
                        dismiss()
                    }
                }

                onCancelListener = object : OnCancelListener<Any> {
                    override fun onCancel(dialog: Dialog, data: Any?) {
                        dismiss()
                    }

                }

                show()
            }


        }

        ll_modify_group_name.setOnClickListener {
            ModifyGroupNameActivity.openActivity(mContext, mRoom.id)
                    .subscribe {
                        if (it.resultCode() == Activity.RESULT_OK) {
                            tv_group_name.text = it.data().getStringExtra("roomName")
                        }
                    }
        }
    }

    private lateinit var mRoom: Room
    private lateinit var member: Member
    private var realm: Realm? = null

    override fun loadData(savedInstanceState: Bundle?) {
        intent.getIntExtra("roomId", -1).apply {
            if (this == -1) {
                finish()
                return
            }
            realm = Realm.getInstance(ChatDB2.getConfiguration())
            mRoom = realm?.where(Room::class.java)
                    ?.equalTo("id", this)
                    ?.findFirst()!!
            member = realm?.where(Member::class.java)
                    ?.equalTo("room", mRoom.id)
                    ?.equalTo("owner.id", ProfileUtil.getUserId())
                    ?.findFirst()!!

            tv_group_name.text = mRoom.name
        }

        HttpMethods.getGroupService()
                .getGroupMember(mRoom.id)
                .compose(bindToLifecycle())
                .compose(RxUtil.applyScheduler())
                .subscribe(object : HttpSubscriber<ListRes<Member>>() {
                    override fun onSuccess(response: ListRes<Member>) {
                        mAdapter?.set(response.results.map {
                            it.owner
                        }, GroupSettingAdapter.HEADER)
                        nbv.titleText = "聊天信息(${response.count})"
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<Member>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)
                    }

                })
    }

    override fun onBackPressed() {
        val intent = Intent()
        intent.putExtra("roomName", tv_group_name.text)
        setResult(Activity.RESULT_OK, intent)
//        super.onBackPressed()
        finish()
    }

    override fun onDestroy() {
        realm?.close()

        super.onDestroy()
    }

}